"""
Agent通信集成器

将智能通信功能集成到现有的Agent Laboratory系统中，包括：
- 增强现有Agent的通信能力
- 集成智能路由到Agent工作流
- 提供统一的通信接口
- 监控和优化Agent间协作
"""
import asyncio
import json
from typing import Dict, List, Any, Optional, Callable
from datetime import datetime, timedelta
from dataclasses import dataclass, field

from .agent_communication_service import (
    AgentCommunicationService, AgentMessage, MessageType, MessagePriority,
    CommunicationProtocol, CollaborationSession
)
from .intelligent_message_router import IntelligentMessageRouter, RoutingStrategy
from .agent_enhancement_service import AgentEnhancementService, AgentRole


@dataclass
class AgentCommunicationConfig:
    """Agent通信配置"""
    agent_id: str
    agent_role: AgentRole
    communication_preferences: Dict[str, Any] = field(default_factory=dict)
    routing_preferences: Dict[str, Any] = field(default_factory=dict)
    collaboration_settings: Dict[str, Any] = field(default_factory=dict)
    notification_settings: Dict[str, Any] = field(default_factory=dict)


class AgentCommunicationIntegrator:
    """Agent通信集成器"""
    
    def __init__(self):
        # 核心服务
        self.communication_service = AgentCommunicationService()
        self.intelligent_router = IntelligentMessageRouter(self.communication_service)
        self.enhancement_service = AgentEnhancementService()
        
        # Agent通信配置
        self.agent_configs: Dict[str, AgentCommunicationConfig] = {}
        
        # 通信拦截器和处理器
        self.message_interceptors: List[Callable] = []
        self.response_handlers: Dict[str, Callable] = {}
        
        # 集成状态
        self.integrated_agents: Dict[str, Any] = {}  # agent_id -> agent_instance
        self.communication_sessions: Dict[str, Dict[str, Any]] = {}
        
        # 性能监控
        self.integration_metrics = {
            'messages_processed': 0,
            'routing_decisions_made': 0,
            'collaboration_sessions_created': 0,
            'performance_improvements': 0.0
        }
    
    async def integrate_agent(self, agent_instance: Any, agent_id: str, agent_role: AgentRole) -> bool:
        """集成Agent到通信系统"""
        try:
            # 创建Agent通信配置
            config = AgentCommunicationConfig(
                agent_id=agent_id,
                agent_role=agent_role,
                communication_preferences={
                    'auto_routing': True,
                    'collaboration_enabled': True,
                    'priority_handling': True,
                    'intelligent_filtering': True
                },
                routing_preferences={
                    'preferred_strategy': RoutingStrategy.CONTEXT_AWARE,
                    'load_balancing': True,
                    'expertise_matching': True
                },
                collaboration_settings={
                    'max_concurrent_sessions': 5,
                    'auto_join_relevant_sessions': True,
                    'session_timeout_hours': 8
                },
                notification_settings={
                    'urgent_message_alerts': True,
                    'collaboration_invites': True,
                    'performance_reports': False
                }
            )
            
            self.agent_configs[agent_id] = config
            self.integrated_agents[agent_id] = agent_instance
            
            # 增强Agent的通信方法
            await self._enhance_agent_communication_methods(agent_instance, agent_id)
            
            # 注册Agent到通信服务
            await self._register_agent_to_communication_service(agent_id, agent_role)
            
            # 初始化Agent的专业知识档案
            await self._initialize_agent_expertise_profile(agent_id, agent_role)
            
            print(f"成功集成Agent: {agent_id} ({agent_role.value})")
            return True
            
        except Exception as e:
            print(f"集成Agent失败: {e}")
            return False
    
    async def _enhance_agent_communication_methods(self, agent_instance: Any, agent_id: str):
        """增强Agent的通信方法"""
        # 保存原始方法
        original_inference = getattr(agent_instance, 'inference', None)
        original_override_inference = getattr(agent_instance, 'override_inference', None)
        
        # 创建增强的推理方法
        async def enhanced_inference(research_topic, phase, step, feedback="", temp=None):
            # 处理接收到的消息
            await self._process_incoming_messages(agent_id)
            
            # 调用原始推理方法
            if original_inference:
                result = original_inference(research_topic, phase, step, feedback, temp)
            else:
                result = "No original inference method found"
            
            # 处理推理结果中的通信指令
            await self._process_communication_commands(agent_id, result, phase)
            
            return result
        
        # 创建增强的覆盖推理方法
        async def enhanced_override_inference(query, temp=0.0):
            # 处理接收到的消息
            await self._process_incoming_messages(agent_id)
            
            # 调用原始方法
            if original_override_inference:
                result = original_override_inference(query, temp)
            else:
                result = "No original override inference method found"
            
            # 处理通信指令
            await self._process_communication_commands(agent_id, result, "override")
            
            return result
        
        # 添加新的通信方法
        async def send_message_to_agent(receiver_id: str, message_type: MessageType, 
                                      subject: str, content: Dict[str, Any],
                                      priority: MessagePriority = MessagePriority.NORMAL,
                                      requires_response: bool = False):
            """发送消息给其他Agent"""
            message = AgentMessage(
                sender_id=agent_id,
                receiver_id=receiver_id,
                message_type=message_type,
                priority=priority,
                subject=subject,
                content=content,
                requires_response=requires_response
            )
            
            return await self.send_intelligent_message(message)
        
        async def join_collaboration_session(session_id: str):
            """加入协作会话"""
            return await self._join_collaboration_session(agent_id, session_id)
        
        async def create_collaboration_session(participants: List[str], session_name: str, 
                                            objectives: List[str]):
            """创建协作会话"""
            return await self.communication_service.create_collaboration_session(
                agent_id, participants, session_name, objectives
            )
        
        async def get_communication_status():
            """获取通信状态"""
            return await self._get_agent_communication_status(agent_id)
        
        # 将增强方法绑定到Agent实例
        setattr(agent_instance, 'enhanced_inference', enhanced_inference)
        setattr(agent_instance, 'enhanced_override_inference', enhanced_override_inference)
        setattr(agent_instance, 'send_message_to_agent', send_message_to_agent)
        setattr(agent_instance, 'join_collaboration_session', join_collaboration_session)
        setattr(agent_instance, 'create_collaboration_session', create_collaboration_session)
        setattr(agent_instance, 'get_communication_status', get_communication_status)
        
        # 添加通信历史访问方法
        setattr(agent_instance, 'get_message_history', 
                lambda: self._get_agent_message_history(agent_id))
        setattr(agent_instance, 'get_collaboration_sessions', 
                lambda: self._get_agent_collaboration_sessions(agent_id))
    
    async def _register_agent_to_communication_service(self, agent_id: str, agent_role: AgentRole):
        """注册Agent到通信服务"""
        # 初始化消息队列
        if agent_id not in self.communication_service.message_queue:
            self.communication_service.message_queue[agent_id] = \
                self.communication_service.message_queue[agent_id]
        
        # 初始化通信指标
        if agent_id not in self.communication_service.communication_metrics:
            from .agent_communication_service import CommunicationMetrics
            self.communication_service.communication_metrics[agent_id] = \
                CommunicationMetrics(agent_id=agent_id)
        
        # 设置Agent角色信息
        self.intelligent_router.agent_expertise[agent_id] = \
            await self._get_default_expertise_for_role(agent_role)
    
    async def _initialize_agent_expertise_profile(self, agent_id: str, agent_role: AgentRole):
        """初始化Agent专业知识档案"""
        expertise_profile = await self._get_default_expertise_for_role(agent_role)
        self.intelligent_router.agent_expertise[agent_id] = expertise_profile
    
    async def _get_default_expertise_for_role(self, agent_role: AgentRole) -> Dict[str, float]:
        """获取角色的默认专业知识"""
        expertise_profiles = {
            AgentRole.PROFESSOR: {
                'research_methodology': 0.9,
                'academic_writing': 0.9,
                'project_management': 0.8,
                'machine_learning': 0.7,
                'data_analysis': 0.6
            },
            AgentRole.PHD_STUDENT: {
                'research_methodology': 0.7,
                'academic_writing': 0.6,
                'machine_learning': 0.8,
                'data_analysis': 0.8,
                'software_engineering': 0.7
            },
            AgentRole.ML_ENGINEER: {
                'machine_learning': 0.9,
                'software_engineering': 0.9,
                'data_analysis': 0.8,
                'research_methodology': 0.5,
                'academic_writing': 0.4
            },
            AgentRole.POSTDOC: {
                'research_methodology': 0.8,
                'academic_writing': 0.7,
                'machine_learning': 0.7,
                'data_analysis': 0.7,
                'project_management': 0.6
            },
            AgentRole.REVIEWER: {
                'academic_writing': 0.8,
                'research_methodology': 0.8,
                'quality_assessment': 0.9,
                'machine_learning': 0.6,
                'data_analysis': 0.6
            }
        }
        
        return expertise_profiles.get(agent_role, {
            'general_knowledge': 0.5,
            'communication': 0.6
        })
    
    async def send_intelligent_message(self, message: AgentMessage) -> bool:
        """发送智能路由消息"""
        try:
            # 应用消息拦截器
            for interceptor in self.message_interceptors:
                message = await interceptor(message)
                if message is None:
                    return False
            
            # 获取智能路由决策
            routing_decision = await self.intelligent_router.route_message_intelligently(message)
            
            # 应用路由决策
            if routing_decision.recommended_receiver != message.receiver_id:
                print(f"路由决策: 将消息从 {message.receiver_id} 重定向到 {routing_decision.recommended_receiver}")
                print(f"路由原因: {routing_decision.reasoning}")
                message.receiver_id = routing_decision.recommended_receiver
                
                # 添加路由信息到消息上下文
                message.context['routing_decision'] = {
                    'original_receiver': routing_decision.original_receiver,
                    'routing_strategy': routing_decision.routing_strategy.value,
                    'confidence_score': routing_decision.confidence_score,
                    'reasoning': routing_decision.reasoning
                }
            
            # 发送消息
            success = await self.communication_service.send_message(message)
            
            if success:
                self.integration_metrics['messages_processed'] += 1
                self.integration_metrics['routing_decisions_made'] += 1
            
            return success
            
        except Exception as e:
            print(f"发送智能消息失败: {e}")
            return False
    
    async def _process_incoming_messages(self, agent_id: str):
        """处理接收到的消息"""
        try:
            # 获取所有待处理消息
            messages = []
            while True:
                message = await self.communication_service.receive_message(agent_id)
                if message is None:
                    break
                messages.append(message)
            
            # 按优先级和类型处理消息
            for message in sorted(messages, key=lambda m: m.priority.value, reverse=True):
                await self._handle_received_message(agent_id, message)
                
        except Exception as e:
            print(f"处理接收消息失败: {e}")
    
    async def _handle_received_message(self, agent_id: str, message: AgentMessage):
        """处理单个接收到的消息"""
        try:
            agent_instance = self.integrated_agents.get(agent_id)
            if not agent_instance:
                return
            
            # 根据消息类型进行处理
            if message.message_type == MessageType.COORDINATION:
                await self._handle_coordination_message(agent_id, message)
            elif message.message_type == MessageType.KNOWLEDGE_SHARE:
                await self._handle_knowledge_share_message(agent_id, message)
            elif message.message_type == MessageType.RESOURCE_SHARE:
                await self._handle_resource_share_message(agent_id, message)
            elif message.message_type == MessageType.NOTIFICATION:
                await self._handle_notification_message(agent_id, message)
            elif message.message_type == MessageType.REQUEST:
                await self._handle_request_message(agent_id, message)
            elif message.message_type == MessageType.RESPONSE:
                await self._handle_response_message(agent_id, message)
            
            # 如果消息需要响应，生成自动响应
            if message.requires_response and message.message_type != MessageType.RESPONSE:
                await self._generate_automatic_response(agent_id, message)
                
        except Exception as e:
            print(f"处理消息失败: {e}")
    
    async def _handle_coordination_message(self, agent_id: str, message: AgentMessage):
        """处理协调消息"""
        content = message.content
        
        if content.get('action') == 'join_session':
            session_id = content.get('session_id')
            if session_id:
                await self._join_collaboration_session(agent_id, session_id)
        
        elif content.get('action') == 'task_assignment':
            # 处理任务分配
            task_info = content.get('task_info', {})
            await self._handle_task_assignment(agent_id, task_info)
        
        elif content.get('action') == 'status_request':
            # 处理状态请求
            await self._send_status_update(agent_id, message.sender_id)
    
    async def _handle_knowledge_share_message(self, agent_id: str, message: AgentMessage):
        """处理知识分享消息"""
        knowledge_data = message.content.get('knowledge_data', {})
        knowledge_type = message.content.get('knowledge_type', 'general')
        
        # 更新Agent的知识库
        agent_instance = self.integrated_agents.get(agent_id)
        if agent_instance and hasattr(agent_instance, 'notes'):
            # 将知识添加到Agent的笔记中
            knowledge_note = {
                'type': 'shared_knowledge',
                'source': message.sender_id,
                'timestamp': message.timestamp.isoformat(),
                'knowledge_type': knowledge_type,
                'data': knowledge_data,
                'phases': ['all']  # 适用于所有阶段
            }
            agent_instance.notes.append(knowledge_note)
    
    async def _handle_resource_share_message(self, agent_id: str, message: AgentMessage):
        """处理资源分享消息"""
        resource_data = message.content.get('resource_data', {})
        resource_type = message.content.get('resource_type', 'data')
        
        # 根据资源类型进行处理
        if resource_type == 'code':
            await self._integrate_shared_code(agent_id, resource_data)
        elif resource_type == 'data':
            await self._integrate_shared_data(agent_id, resource_data)
        elif resource_type == 'results':
            await self._integrate_shared_results(agent_id, resource_data)
    
    async def _handle_notification_message(self, agent_id: str, message: AgentMessage):
        """处理通知消息"""
        notification_type = message.content.get('notification_type', 'general')
        
        if notification_type == 'session_invite':
            session_id = message.content.get('session_id')
            auto_join = self.agent_configs[agent_id].collaboration_settings.get('auto_join_relevant_sessions', True)
            
            if auto_join and session_id:
                await self._join_collaboration_session(agent_id, session_id)
        
        elif notification_type == 'urgent_alert':
            # 处理紧急警报
            await self._handle_urgent_alert(agent_id, message)
    
    async def _handle_request_message(self, agent_id: str, message: AgentMessage):
        """处理请求消息"""
        request_type = message.content.get('request_type', 'general')
        
        if request_type == 'expertise_consultation':
            # 处理专业咨询请求
            await self._handle_expertise_consultation(agent_id, message)
        elif request_type == 'collaboration_request':
            # 处理协作请求
            await self._handle_collaboration_request(agent_id, message)
        elif request_type == 'resource_request':
            # 处理资源请求
            await self._handle_resource_request(agent_id, message)
    
    async def _handle_response_message(self, agent_id: str, message: AgentMessage):
        """处理响应消息"""
        original_message_id = message.context.get('original_message_id')
        
        if original_message_id and original_message_id in self.response_handlers:
            handler = self.response_handlers[original_message_id]
            await handler(message)
            del self.response_handlers[original_message_id]
    
    async def _generate_automatic_response(self, agent_id: str, message: AgentMessage):
        """生成自动响应"""
        try:
            agent_instance = self.integrated_agents.get(agent_id)
            if not agent_instance:
                return
            
            # 根据消息类型生成响应内容
            response_content = {}
            
            if message.message_type == MessageType.REQUEST:
                request_type = message.content.get('request_type', 'general')
                
                if request_type == 'status_request':
                    response_content = await self._generate_status_response(agent_id)
                elif request_type == 'expertise_consultation':
                    response_content = await self._generate_expertise_response(agent_id, message)
                else:
                    response_content = {
                        'status': 'received',
                        'message': f'已收到请求，正在处理',
                        'estimated_response_time': '30分钟'
                    }
            
            elif message.message_type == MessageType.COORDINATION:
                response_content = {
                    'status': 'acknowledged',
                    'message': '已确认协调指令',
                    'next_action': '等待进一步指示'
                }
            
            else:
                response_content = {
                    'status': 'received',
                    'message': '消息已收到并处理'
                }
            
            # 发送响应
            await self.communication_service.send_response(
                message.message_id, response_content, agent_id
            )
            
        except Exception as e:
            print(f"生成自动响应失败: {e}")
    
    async def _generate_status_response(self, agent_id: str) -> Dict[str, Any]:
        """生成状态响应"""
        agent_instance = self.integrated_agents.get(agent_id)
        
        status = {
            'agent_id': agent_id,
            'current_phase': getattr(agent_instance, 'current_phase', 'unknown'),
            'workload': self.intelligent_router.agent_workload.get(agent_id, 0.0),
            'active_sessions': len([s for s in self.communication_service.collaboration_sessions.values()
                                  if agent_id in s.participants and s.status == 'active']),
            'message_queue_length': len(self.communication_service.message_queue.get(agent_id, [])),
            'last_activity': datetime.now().isoformat()
        }
        
        return status
    
    async def _generate_expertise_response(self, agent_id: str, message: AgentMessage) -> Dict[str, Any]:
        """生成专业知识响应"""
        expertise_area = message.content.get('expertise_area', 'general')
        question = message.content.get('question', '')
        
        agent_expertise = self.intelligent_router.agent_expertise.get(agent_id, {})
        expertise_level = agent_expertise.get(expertise_area, 0.0)
        
        if expertise_level > 0.7:
            response = {
                'expertise_level': 'high',
                'can_help': True,
                'response': f'我在{expertise_area}领域有较高专业水平，可以协助解答',
                'suggested_approach': '建议安排详细讨论会议'
            }
        elif expertise_level > 0.4:
            response = {
                'expertise_level': 'medium',
                'can_help': True,
                'response': f'我在{expertise_area}领域有一定了解，可以提供基础帮助',
                'suggested_approach': '可以提供初步建议，复杂问题建议咨询专家'
            }
        else:
            # 寻找更合适的专家
            better_expert = await self.intelligent_router._find_best_expert([expertise_area])
            response = {
                'expertise_level': 'low',
                'can_help': False,
                'response': f'我在{expertise_area}领域专业水平有限',
                'suggested_expert': better_expert,
                'suggested_approach': f'建议咨询{better_expert}获得专业帮助' if better_expert else '建议寻找该领域专家'
            }
        
        return response
    
    async def _process_communication_commands(self, agent_id: str, agent_output: str, phase: str):
        """处理Agent输出中的通信指令"""
        try:
            # 检查是否包含通信指令
            if '```SEND_MESSAGE' in agent_output:
                await self._process_send_message_command(agent_id, agent_output)
            
            if '```CREATE_SESSION' in agent_output:
                await self._process_create_session_command(agent_id, agent_output)
            
            if '```JOIN_SESSION' in agent_output:
                await self._process_join_session_command(agent_id, agent_output)
            
            if '```SHARE_KNOWLEDGE' in agent_output:
                await self._process_share_knowledge_command(agent_id, agent_output)
            
            if '```REQUEST_HELP' in agent_output:
                await self._process_request_help_command(agent_id, agent_output)
                
        except Exception as e:
            print(f"处理通信指令失败: {e}")
    
    async def _process_send_message_command(self, agent_id: str, agent_output: str):
        """处理发送消息指令"""
        # 解析消息指令
        import re
        pattern = r'```SEND_MESSAGE\n(.*?)\n```'
        matches = re.findall(pattern, agent_output, re.DOTALL)
        
        for match in matches:
            try:
                # 解析消息内容（假设是JSON格式）
                message_data = json.loads(match)
                
                message = AgentMessage(
                    sender_id=agent_id,
                    receiver_id=message_data.get('receiver_id', ''),
                    message_type=MessageType(message_data.get('message_type', 'request')),
                    priority=MessagePriority(message_data.get('priority', 2)),
                    subject=message_data.get('subject', ''),
                    content=message_data.get('content', {}),
                    requires_response=message_data.get('requires_response', False)
                )
                
                await self.send_intelligent_message(message)
                
            except Exception as e:
                print(f"解析发送消息指令失败: {e}")
    
    async def _process_create_session_command(self, agent_id: str, agent_output: str):
        """处理创建会话指令"""
        import re
        pattern = r'```CREATE_SESSION\n(.*?)\n```'
        matches = re.findall(pattern, agent_output, re.DOTALL)
        
        for match in matches:
            try:
                session_data = json.loads(match)
                
                session_id = await self.communication_service.create_collaboration_session(
                    coordinator_id=agent_id,
                    participants=session_data.get('participants', []),
                    session_name=session_data.get('name', ''),
                    objectives=session_data.get('objectives', [])
                )
                
                if session_id:
                    self.integration_metrics['collaboration_sessions_created'] += 1
                
            except Exception as e:
                print(f"解析创建会话指令失败: {e}")
    
    async def _process_join_session_command(self, agent_id: str, agent_output: str):
        """处理加入会话指令"""
        import re
        pattern = r'```JOIN_SESSION\n(.*?)\n```'
        matches = re.findall(pattern, agent_output, re.DOTALL)
        
        for match in matches:
            try:
                session_data = json.loads(match)
                session_id = session_data.get('session_id', '')
                
                if session_id:
                    await self._join_collaboration_session(agent_id, session_id)
                
            except Exception as e:
                print(f"解析加入会话指令失败: {e}")
    
    async def _process_share_knowledge_command(self, agent_id: str, agent_output: str):
        """处理分享知识指令"""
        import re
        pattern = r'```SHARE_KNOWLEDGE\n(.*?)\n```'
        matches = re.findall(pattern, agent_output, re.DOTALL)
        
        for match in matches:
            try:
                knowledge_data = json.loads(match)
                
                # 创建知识分享消息
                message = AgentMessage(
                    sender_id=agent_id,
                    receiver_id=knowledge_data.get('target_agent', ''),
                    message_type=MessageType.KNOWLEDGE_SHARE,
                    priority=MessagePriority.NORMAL,
                    subject=f"知识分享: {knowledge_data.get('topic', '未指定主题')}",
                    content={
                        'knowledge_type': knowledge_data.get('knowledge_type', 'general'),
                        'knowledge_data': knowledge_data.get('data', {}),
                        'source_phase': knowledge_data.get('source_phase', 'unknown')
                    }
                )
                
                await self.send_intelligent_message(message)
                
            except Exception as e:
                print(f"解析分享知识指令失败: {e}")
    
    async def _process_request_help_command(self, agent_id: str, agent_output: str):
        """处理请求帮助指令"""
        import re
        pattern = r'```REQUEST_HELP\n(.*?)\n```'
        matches = re.findall(pattern, agent_output, re.DOTALL)
        
        for match in matches:
            try:
                help_request = json.loads(match)
                
                # 寻找最合适的帮助者
                expertise_required = help_request.get('expertise_required', [])
                best_helper = await self.intelligent_router._find_best_expert(expertise_required)
                
                if best_helper:
                    message = AgentMessage(
                        sender_id=agent_id,
                        receiver_id=best_helper,
                        message_type=MessageType.REQUEST,
                        priority=MessagePriority.HIGH,
                        subject=f"请求协助: {help_request.get('topic', '未指定主题')}",
                        content={
                            'request_type': 'expertise_consultation',
                            'expertise_area': expertise_required[0] if expertise_required else 'general',
                            'question': help_request.get('question', ''),
                            'urgency': help_request.get('urgency', 'normal'),
                            'context': help_request.get('context', {})
                        },
                        requires_response=True
                    )
                    
                    await self.send_intelligent_message(message)
                
            except Exception as e:
                print(f"解析请求帮助指令失败: {e}")
    
    async def _join_collaboration_session(self, agent_id: str, session_id: str) -> bool:
        """加入协作会话"""
        try:
            if session_id not in self.communication_service.collaboration_sessions:
                return False
            
            session = self.communication_service.collaboration_sessions[session_id]
            
            if agent_id not in session.participants:
                session.participants.append(agent_id)
                self.communication_service.active_sessions[agent_id] = session_id
                
                # 发送加入通知
                join_message = AgentMessage(
                    sender_id=agent_id,
                    receiver_id=session.coordinator_id,
                    message_type=MessageType.NOTIFICATION,
                    subject=f"已加入协作会话: {session.name}",
                    content={
                        'action': 'session_joined',
                        'session_id': session_id,
                        'participant': agent_id
                    }
                )
                
                await self.communication_service.send_message(join_message)
                return True
            
            return True
            
        except Exception as e:
            print(f"加入协作会话失败: {e}")
            return False
    
    async def _get_agent_communication_status(self, agent_id: str) -> Dict[str, Any]:
        """获取Agent通信状态"""
        try:
            status = {
                'agent_id': agent_id,
                'message_queue_length': len(self.communication_service.message_queue.get(agent_id, [])),
                'active_sessions': [],
                'recent_messages': [],
                'communication_metrics': {},
                'routing_preferences': self.agent_configs.get(agent_id, {}).routing_preferences
            }
            
            # 获取活跃会话
            for session_id, session in self.communication_service.collaboration_sessions.items():
                if agent_id in session.participants and session.status == 'active':
                    status['active_sessions'].append({
                        'session_id': session_id,
                        'name': session.name,
                        'coordinator': session.coordinator_id,
                        'participants_count': len(session.participants)
                    })
            
            # 获取最近消息
            recent_messages = []
            cutoff_time = datetime.now() - timedelta(hours=24)
            
            for message in self.communication_service.message_history.values():
                if ((message.sender_id == agent_id or message.receiver_id == agent_id) and 
                    message.timestamp > cutoff_time):
                    recent_messages.append({
                        'message_id': message.message_id,
                        'sender': message.sender_id,
                        'receiver': message.receiver_id,
                        'type': message.message_type.value,
                        'subject': message.subject,
                        'timestamp': message.timestamp.isoformat()
                    })
            
            status['recent_messages'] = sorted(recent_messages, 
                                             key=lambda x: x['timestamp'], reverse=True)[:10]
            
            # 获取通信指标
            metrics = await self.communication_service.get_communication_metrics(agent_id)
            status['communication_metrics'] = metrics
            
            return status
            
        except Exception as e:
            print(f"获取通信状态失败: {e}")
            return {'error': '获取状态失败'}
    
    async def _get_agent_message_history(self, agent_id: str) -> List[Dict[str, Any]]:
        """获取Agent消息历史"""
        history = []
        
        for message in self.communication_service.message_history.values():
            if message.sender_id == agent_id or message.receiver_id == agent_id:
                history.append({
                    'message_id': message.message_id,
                    'sender': message.sender_id,
                    'receiver': message.receiver_id,
                    'type': message.message_type.value,
                    'priority': message.priority.value,
                    'subject': message.subject,
                    'content': message.content,
                    'timestamp': message.timestamp.isoformat(),
                    'delivery_status': message.delivery_status
                })
        
        return sorted(history, key=lambda x: x['timestamp'], reverse=True)
    
    async def _get_agent_collaboration_sessions(self, agent_id: str) -> List[Dict[str, Any]]:
        """获取Agent协作会话"""
        sessions = []
        
        for session_id, session in self.communication_service.collaboration_sessions.items():
            if agent_id in session.participants:
                sessions.append({
                    'session_id': session_id,
                    'name': session.name,
                    'coordinator': session.coordinator_id,
                    'participants': session.participants,
                    'status': session.status,
                    'objectives': session.objectives,
                    'start_time': session.start_time.isoformat(),
                    'end_time': session.end_time.isoformat() if session.end_time else None
                })
        
        return sessions
    
    async def optimize_system_communication(self) -> Dict[str, Any]:
        """优化系统通信"""
        try:
            optimization_results = {
                'routing_optimization': {},
                'bottleneck_resolution': {},
                'collaboration_optimization': {},
                'performance_improvement': 0.0
            }
            
            # 优化路由
            routing_results = await self.intelligent_router.optimize_communication_routes()
            optimization_results['routing_optimization'] = routing_results
            
            # 解决瓶颈
            bottleneck_results = await self.intelligent_router.detect_and_resolve_bottlenecks()
            optimization_results['bottleneck_resolution'] = bottleneck_results
            
            # 优化协作会话
            collaboration_optimizations = []
            for session_id in self.communication_service.collaboration_sessions:
                optimization = await self.intelligent_router.optimize_collaboration_pattern(session_id)
                collaboration_optimizations.append(optimization)
            
            optimization_results['collaboration_optimization'] = {
                'sessions_analyzed': len(collaboration_optimizations),
                'optimizations': collaboration_optimizations
            }
            
            # 计算总体性能改善
            total_improvement = (
                routing_results.get('efficiency_improvement', 0.0) * 0.4 +
                bottleneck_results.get('system_health_improvement', 0.0) * 0.3 +
                sum(opt.expected_improvement for opt in collaboration_optimizations) / 
                len(collaboration_optimizations) * 0.3 if collaboration_optimizations else 0.0
            )
            
            optimization_results['performance_improvement'] = total_improvement
            self.integration_metrics['performance_improvements'] += total_improvement
            
            return optimization_results
            
        except Exception as e:
            print(f"优化系统通信失败: {e}")
            return {'error': '通信优化失败'}
    
    async def get_integration_analytics(self) -> Dict[str, Any]:
        """获取集成分析报告"""
        try:
            analytics = {
                'integration_metrics': dict(self.integration_metrics),
                'agent_status': {},
                'communication_patterns': {},
                'routing_analytics': {},
                'collaboration_analytics': {},
                'recommendations': []
            }
            
            # 获取所有集成Agent的状态
            for agent_id in self.integrated_agents:
                status = await self._get_agent_communication_status(agent_id)
                analytics['agent_status'][agent_id] = status
            
            # 获取通信模式分析
            analytics['communication_patterns'] = await self._analyze_communication_patterns()
            
            # 获取路由分析
            analytics['routing_analytics'] = await self.intelligent_router.get_routing_analytics()
            
            # 获取协作分析
            analytics['collaboration_analytics'] = await self._analyze_collaboration_effectiveness()
            
            # 生成改进建议
            analytics['recommendations'] = await self._generate_improvement_recommendations()
            
            return analytics
            
        except Exception as e:
            print(f"获取集成分析失败: {e}")
            return {'error': '分析获取失败'}
    
    async def _analyze_communication_patterns(self) -> Dict[str, Any]:
        """分析通信模式"""
        patterns = {
            'message_volume_by_hour': {},
            'communication_pairs': {},
            'message_type_distribution': {},
            'response_time_trends': {}
        }
        
        try:
            cutoff_time = datetime.now() - timedelta(days=7)
            
            for message in self.communication_service.message_history.values():
                if message.timestamp > cutoff_time:
                    # 按小时统计消息量
                    hour = message.timestamp.hour
                    patterns['message_volume_by_hour'][hour] = \
                        patterns['message_volume_by_hour'].get(hour, 0) + 1
                    
                    # 统计通信对
                    pair = f"{message.sender_id}->{message.receiver_id}"
                    patterns['communication_pairs'][pair] = \
                        patterns['communication_pairs'].get(pair, 0) + 1
                    
                    # 统计消息类型分布
                    msg_type = message.message_type.value
                    patterns['message_type_distribution'][msg_type] = \
                        patterns['message_type_distribution'].get(msg_type, 0) + 1
            
        except Exception as e:
            print(f"分析通信模式失败: {e}")
        
        return patterns
    
    async def _analyze_collaboration_effectiveness(self) -> Dict[str, Any]:
        """分析协作效果"""
        effectiveness = {
            'active_sessions_count': 0,
            'average_session_duration': 0.0,
            'participation_rates': {},
            'objective_completion_rates': {},
            'collaboration_satisfaction': 0.0
        }
        
        try:
            active_sessions = [s for s in self.communication_service.collaboration_sessions.values()
                             if s.status == 'active']
            effectiveness['active_sessions_count'] = len(active_sessions)
            
            if active_sessions:
                # 计算平均会话持续时间
                total_duration = 0
                for session in active_sessions:
                    duration = (datetime.now() - session.start_time).total_seconds()
                    total_duration += duration
                
                effectiveness['average_session_duration'] = total_duration / len(active_sessions) / 3600  # 小时
                
                # 计算参与率
                for session in active_sessions:
                    session_messages = [msg for msg in self.communication_service.message_history.values()
                                      if msg.context.get('session_id') == session.session_id]
                    
                    participant_activity = {}
                    for participant in session.participants:
                        activity_count = sum(1 for msg in session_messages if msg.sender_id == participant)
                        participant_activity[participant] = activity_count
                    
                    if participant_activity:
                        avg_activity = sum(participant_activity.values()) / len(session.participants)
                        effectiveness['participation_rates'][session.session_id] = {
                            'average_messages_per_participant': avg_activity,
                            'participant_activity': participant_activity
                        }
                
                # 计算目标完成率
                for session in active_sessions:
                    completed_objectives = len([obj for obj in session.decisions_made 
                                              if obj.get('status') == 'completed'])
                    total_objectives = len(session.objectives)
                    completion_rate = completed_objectives / total_objectives if total_objectives > 0 else 0.0
                    effectiveness['objective_completion_rates'][session.session_id] = completion_rate
            
        except Exception as e:
            print(f"分析协作效果失败: {e}")
        
        return effectiveness
    
    async def _generate_improvement_recommendations(self) -> List[Dict[str, Any]]:
        """生成改进建议"""
        recommendations = []
        
        try:
            # 基于通信指标生成建议
            for agent_id in self.integrated_agents:
                metrics = await self.communication_service.get_communication_metrics(agent_id)
                
                if metrics.get('communication_efficiency', 0) < 0.6:
                    recommendations.append({
                        'type': 'communication_efficiency',
                        'target': agent_id,
                        'priority': 'medium',
                        'description': f'Agent {agent_id} 的通信效率较低，建议优化消息处理流程',
                        'suggested_actions': [
                            '启用智能消息过滤',
                            '优化响应时间',
                            '增加自动化响应'
                        ]
                    })
                
                if metrics.get('collaboration_score', 0) < 0.5:
                    recommendations.append({
                        'type': 'collaboration_improvement',
                        'target': agent_id,
                        'priority': 'high',
                        'description': f'Agent {agent_id} 的协作参与度较低，建议增加协作活动',
                        'suggested_actions': [
                            '主动参与协作会话',
                            '增加知识分享',
                            '提供更多协助'
                        ]
                    })
            
            # 基于系统整体性能生成建议
            if self.integration_metrics['routing_decisions_made'] > 0:
                routing_analytics = await self.intelligent_router.get_routing_analytics()
                
                for opportunity in routing_analytics.get('optimization_opportunities', []):
                    recommendations.append({
                        'type': 'system_optimization',
                        'target': 'system',
                        'priority': opportunity.get('priority', 'medium'),
                        'description': opportunity.get('description', ''),
                        'suggested_actions': [opportunity.get('type', '')]
                    })
            
        except Exception as e:
            print(f"生成改进建议失败: {e}")
        
        return recommendations
    
    def add_message_interceptor(self, interceptor: Callable):
        """添加消息拦截器"""
        self.message_interceptors.append(interceptor)
    
    def add_response_handler(self, message_id: str, handler: Callable):
        """添加响应处理器"""
        self.response_handlers[message_id] = handler
    
    async def shutdown(self):
        """关闭集成器"""
        try:
            # 结束所有活跃的协作会话
            for session_id, session in self.communication_service.collaboration_sessions.items():
                if session.status == 'active':
                    await self.communication_service.end_collaboration_session(session_id, session.coordinator_id)
            
            # 清理资源
            self.integrated_agents.clear()
            self.agent_configs.clear()
            self.communication_sessions.clear()
            
            print("Agent通信集成器已关闭")
            
        except Exception as e:
            print(f"关闭集成器失败: {e}")